﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using Telerik.Windows.Data;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Workflow.Models;

namespace Rio.Flow.Application.Models.Flow
{
    public class DataViewModel : INotifyPropertyChanged
    {
        #region Fields

        private QueryableCollectionView m_SelectedItemListMessage;
        private DataItemTreeViewCollection _itemsTreeView;

        #endregion Fields

        #region Constructors

        public DataViewModel()
        {
            ItemsTreeView = new DataItemTreeViewCollection(null);
            SelectedItemListMessage = new QueryableCollectionView(new List<Framework.Pages.AppCode.Models.MessageFlowDisp>());

            BeginLoadingItems();
        }

        #endregion Constructors

        #region Events

        public event EventHandler Loaded;

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion Events

        #region Properties

        /// <summary>
        /// Gets or sets the items tree view.
        /// </summary>
        /// <value>The items tree view.</value>
        public DataItemTreeViewCollection ItemsTreeView
        {
            get { return _itemsTreeView; }
            set
            {
                _itemsTreeView = value;
                OnPropertyChanged("ItemsTreeView");
            }
        }

        /// <summary>
        /// Gets or sets the selected item list message.
        /// </summary>
        /// <value>The selected item list message.</value>
        public QueryableCollectionView SelectedItemListMessage
        {
            get
            {
                return m_SelectedItemListMessage;
            }
            set
            {
                if (m_SelectedItemListMessage != value)
                {
                    m_SelectedItemListMessage = value;
                    OnPropertyChanged("SelectedItemListMessage");
                }
            }
        }

        #endregion Properties

        #region Methods

        public void MessagesLoaded(DataItemTreeView selectedItem = null)
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            ( (WebDomainClient<BusinessEntitiesDomainContext.IBusinessEntitiesDomainServiceContract>)l_oBEDomainContext.DomainClient ).ChannelFactory.Endpoint.Binding.SendTimeout = new TimeSpan(1, 0, 0);

            var MessageFlowSentByMe_Query = l_oBEDomainContext.GetMessageFlowSentByMeQuery();
            l_oBEDomainContext.Load(MessageFlowSentByMe_Query, OnGetMessageFlowSentByMeCallback, selectedItem);

            var MessageFlowInMyBox_Query = l_oBEDomainContext.GetMessageFlowInMyBoxQuery();
            l_oBEDomainContext.Load(MessageFlowInMyBox_Query, OnGetMessageFlowInMyBoxCallback, selectedItem);
        }

        public void OnGetMessageFlowInMyBoxCallback(LoadOperation<MessageFlow> result)
        {
            try
            {
                List<MessageFlow> l_oMessageFlows = new List<MessageFlow>(result.Entities);
                List<Framework.Pages.AppCode.Models.MessageFlowDisp> l_oMessageFlowsDisp = new List<Framework.Pages.AppCode.Models.MessageFlowDisp>();

                if (l_oMessageFlows != null)
                {
                    MessageFlow l_oMessageFlow = l_oMessageFlows.First();

                    if (!l_oMessageFlow.IsValid)
                    {
                        throw new Exception(l_oMessageFlow.FullErrorMessage);
                    }
                    else
                    {
                        int l_oNewItem = 0;

                        DataItemTreeView receipt = ItemsTreeView[0];

                        foreach (MessageFlow l_oMsg in l_oMessageFlows)
                        {
                            if (l_oMsg.MyDocEtat == 0)
                            {
                                l_oNewItem++;

                            }

                            l_oMessageFlowsDisp.Add(new Framework.Pages.AppCode.Models.MessageFlowDisp(l_oMsg));
                        }

                        receipt.NumberNewItem = l_oNewItem;
                        receipt.NumberItem = l_oMessageFlowsDisp.Count;
                        receipt.CollectionMessage = new QueryableCollectionView(l_oMessageFlowsDisp);

                        Loaded(this, new EventArgs());

                        //Re-select item
                        if (result.UserState != null)
                        {
                            var dataItemTreeView = result.UserState as DataItemTreeView;
                            if (dataItemTreeView != null && dataItemTreeView.ItemType == WorkflowTreeItemType.Reception)
                            {
                                SelectedItemListMessage = receipt.CollectionMessage;
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("No Message retrieved");
                }
            }
            catch (Exception)
            {
                //ModalDialogController.Launch<Message>(new Message(" -> OnGetMessageFlowSentByMeCallback failure Error : " + Environment.NewLine, ex));
            }
        }

        public void OnGetMessageFlowSentByMeCallback(LoadOperation<MessageFlow> result)
        {
            try
            {
                List<MessageFlow> l_oMessageFlows = new List<MessageFlow>(result.Entities);
                List<Framework.Pages.AppCode.Models.MessageFlowDisp> l_oMessageFlowsDisp = new List<Framework.Pages.AppCode.Models.MessageFlowDisp>();

                if (l_oMessageFlows != null)
                {
                    MessageFlow l_oMessageFlow = l_oMessageFlows.First();

                    if (!l_oMessageFlow.IsValid)
                    {
                        throw new Exception(l_oMessageFlow.FullErrorMessage);
                    }
                    else
                    {
                        DataItemTreeView send = ItemsTreeView[1];

                        int l_oNewItem = 0;

                        foreach (MessageFlow l_oMsg in l_oMessageFlows)
                        {
                            int resultComp = DateTime.Compare(l_oMsg.LastReadDate, l_oMsg.LastActionDate);

                            bool l_bRead = true;

                            if (resultComp < 0)
                            {
                                l_oNewItem++;
                                l_bRead = false;
                            }

                            Framework.Pages.AppCode.Models.MessageFlowDisp l_oMsgDisp = new Framework.Pages.AppCode.Models.MessageFlowDisp(l_oMsg);

                            l_oMsgDisp.MyDocEtat = l_bRead ? 1 : 0;

                            l_oMessageFlowsDisp.Add(l_oMsgDisp);
                        }

                        send.NumberNewItem = l_oNewItem;
                        send.NumberItem = l_oMessageFlowsDisp.Count;
                        send.CollectionMessage = new QueryableCollectionView(l_oMessageFlowsDisp);

                        //Re-select item
                        var dataItemTreeView = result.UserState as DataItemTreeView;
                        if (dataItemTreeView != null)
                        {
                            if ((dataItemTreeView).ItemType == WorkflowTreeItemType.Send)
                            {
                                SelectedItemListMessage = send.CollectionMessage;
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("No Message retrieved");
                }
            }
            catch (Exception)
            {
                //ModalDialogController.Launch<Message>(new Message(" -> OnGetMessageFlowSentByMeCallback failure Error : " + Environment.NewLine, ex));
            }
        }

        public void OnPropertyChanged(string P_PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(P_PropertyName));
            }
        }

        private void BeginLoadingItems()
        {
            ItemsLoaded();
            MessagesLoaded();
        }

        private void ItemsLoaded()
        {
            /*
             * Receive
             */

            DataItemTreeView L_Receipt = new DataItemTreeView();
            L_Receipt.iIdRepertory = (int)Repertory.RECEIPT;
            L_Receipt.ItemType = WorkflowTreeItemType.Reception;
            L_Receipt.SubItemType = WorkflowTreeSubItemType.None;
            L_Receipt.sText = Resx.GetLabel(ResxFlowPage.FLOW_RECEIVE);
            L_Receipt.sImageSrc = "../../Assets/Images/Mail_receive.png";
            L_Receipt.bIsExpanded = true;

            L_Receipt.bIsDropAllowed = false;
            L_Receipt.CollectionMessage = new QueryableCollectionView(new List<Framework.Pages.AppCode.Models.MessageFlowDisp>());
            ItemsTreeView.Add(L_Receipt);

            /*
             * Send
             */

            DataItemTreeView L_Send = new DataItemTreeView();
            L_Send.iIdRepertory = (int)Repertory.SEND;
            L_Send.ItemType = WorkflowTreeItemType.Send;
            L_Send.SubItemType = WorkflowTreeSubItemType.None;
            L_Send.sText = Resx.GetLabel(ResxFlowPage.FLOW_SENT);
            L_Send.bIsExpanded = true;
            L_Send.sImageSrc = "../../Assets/Images/Mail_send.png";
            L_Send.bIsDropAllowed = false;
            L_Receipt.CollectionMessage = new QueryableCollectionView(new List<Framework.Pages.AppCode.Models.MessageFlowDisp>());
            ItemsTreeView.Add(L_Send);
        }

        #endregion Methods
    }
}